package egovframework.npqs.pqi.mobile.jsonparser;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.common.Const;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.util.ParameterUtil;

public class FruitPackingUpdateThread extends Thread{
	
	public interface FruitPackingUpdateThreadCallBack{
		public void OnFruitPackingUpdateCompleted(boolean isNetworkConntected, String result);
		public void OnFruitPackingUpdateError(ErrorItem errorItem);
	}
	
	private String url;
	private FruitPackingUpdateThreadCallBack callback;
	private ArrayList<NameValuePair> post;
	private Context context;
	private AppStatus appStatus;

	private String resultData;
	public FruitPackingUpdateThread(Context context, FruitPackingUpdateThreadCallBack callback, String resultData) {
		this.context = context;
		this.callback = callback;
		this.appStatus = (AppStatus) context.getApplicationContext();
		this.resultData = resultData;
	}
	
	@Override
	public void run() {
		// 통신불통상태이면
		if(!appStatus.utilm.isNetworkConnected(context)) {
			callback.OnFruitPackingUpdateCompleted(false, "");
			return;
		}
		JSONParser jParser = new JSONParser();

		url = Const.MAIN_URL;
		post =  ParameterUtil.getFruitPackingUpdateParams(resultData);
		
		JSONObject json = jParser.getJSONFromUrl(url, post);
		Log.i("url","url : "+url);
		Log.i("post","post : "+post);
		Log.i("json","json : "+json);
		
		if(json == null) {	// json 값이 null 일때
			callback.OnFruitPackingUpdateError(null);
			return;
		}
		try {		
			int result = json.getInt(Const.RESULT);
			String data = json.getString(Const.DATA);
			Log.i("data", data);
			if(result == 0){	// result 값이 0일 경우
				ErrorItem errorItem = new ErrorItem();
				errorItem.setrDesc(data);
				callback.OnFruitPackingUpdateError(errorItem);
			}else{	// result 값이 0이 아닐 경우
				callback.OnFruitPackingUpdateCompleted(true, data);
			}
			
		} catch (JSONException e) {
			
		}
	}
}
